// Likelihood.cpp: implementation of the Likelihood class.
//
//////////////////////////////////////////////////////////////////////

#include <iostream>
#include "Likelihood.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////


Likelihood::Likelihood(DataHolder *Measurement)
{
  int n;

  Data = new DataHolder(*Measurement);

  NInput = Data->N;

  //for (int i = 1; i <= NInput; i++)
  //{
  //  cout << Data->Average[i] << endl;
  //  cout << Data->Hessian[i];
  //}



  newA(Hd, NInput); // hessian * observed data
  newA(Hf, NInput); // hessian * calculated data

  for(n=1;n<=NInput;n++)
	  Hd[n] = Data->Hessian[n] * Data->Average;

  dHd = 0.0;
  for(n=1;n<=NInput;n++)
	  dHd  += Data->Average[n] * Hd[n];
}


Likelihood::~Likelihood()
{
delete Data;

deleteA(Hd);
deleteA(Hf);
}


//////////////////////////////////////////////////////////////////////
// functions
//////////////////////////////////////////////////////////////////////


double Likelihood::Build(double *Input)
{
  int n;

  for(n=1;n<=NInput;n++)
	  Hf[n] = Data->Hessian[n] * Input;

  fHd = 0.0;
  fHf = 0.0;
  for(n=1;n<=NInput;n++)
	{
	fHd += Input[n]*Hd[n];
	fHf += Input[n]*Hf[n];
	}

  ChiSquared = dHd - fHd*fHd/fHf;

  ChiSquared /= double(NInput);

  return (ChiSquared/2.0);
}


void Likelihood::BuildDerivatives(double *InputDerivative)
{
double v1 = -fHd/fHf;
double v2 = v1*v1;

//v1 /= (double(NInput) * (Temp)); // devide potential by Temp
//v2 /= (double(NInput) * (Temp));

v1 /= double(NInput); 
v2 /= double(NInput);

for(int n=1;n<=NInput;n++)
	InputDerivative[n] = v2*Hf[n] + v1*Hd[n];
}

